package yxy.game.pm2.module.union.war;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Map;

import org.joda.time.DateTime;

import yxy.apple.util.RandomUtility;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.unionfightbox;
import yxy.cherry.data.bean.unionfightrankreward;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionModule;

public class UnionWarUnionModule extends UnionModule {

	private String oppoUnionCode;// 对手联盟Code
	private ArrayList<String> forts = new ArrayList<>();// 据点code
	private HashSet<String> entrySet = new HashSet<>(); // 参赛名单
	private ArrayList<UnionWarBox> boxes = new ArrayList<>();
	private HashSet<String> boxGetter = new HashSet<>(); // 已领奖名单

	private ArrayList<UnionWarLogBean> logs = new ArrayList<>();

	private int buff;// 增益层数
	private boolean win;// 是否胜利

	// 联盟快照
	private String name;
	private int level;
	private long power;

	private int areaGroupId;

	public String getOppoUnionCode() {
		return oppoUnionCode;
	}

	public void setOppoUnionCode(String oppoUnionCode) {
		this.oppoUnionCode = oppoUnionCode;
	}

	public ArrayList<String> getForts() {
		return forts;
	}

	public void setForts(ArrayList<String> forts) {
		this.forts = forts;
	}

	public HashSet<String> getEntrySet() {
		return entrySet;
	}

	public void setEntrySet(HashSet<String> entrySet) {
		this.entrySet = entrySet;
	}

	public ArrayList<UnionWarBox> getBoxes() {
		return boxes;
	}

	public void setBoxes(ArrayList<UnionWarBox> boxes) {
		this.boxes = boxes;
	}

	public HashSet<String> getBoxGetter() {
		return boxGetter;
	}

	public void setBoxGetter(HashSet<String> boxGetter) {
		this.boxGetter = boxGetter;
	}

	public int getBuff() {
		return buff;
	}

	public void setBuff(int buff) {
		this.buff = buff;
	}

	public boolean isWin() {
		return win;
	}

	public void setWin(boolean win) {
		this.win = win;
	}

	public ArrayList<UnionWarLogBean> getLogs() {
		return logs;
	}

	public void setLogs(ArrayList<UnionWarLogBean> logs) {
		this.logs = logs;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public long getPower() {
		return power;
	}

	public void setPower(long power) {
		this.power = power;
	}

	// func==========================================================================
	// 联盟获得的星星数
	public int star() {
		UnionWarUnionModule oppo = UnionWarUnionModule.get(getOppoUnionCode());
		if (oppo == null) {
			return 0;
		}
		int star = 0;
		Collection<UnionWarFort> forts = UnionWarFort.all(getOppoUnionCode()).values();
		for (UnionWarFort fort : forts) {
			star += fort.getStar();
		}
		return star;
	}

	/** 总战绩 */
	public long totalScore() {
		long score = 0;
		RankUnionWar rank = new RankUnionWar(getUnionCode());
		Collection<RankEntry> all = rank.range(0, -1);
		for (RankEntry entry : all) {
			score += entry.getValue();
		}
		return score;
	}

	/** 处理宝箱 */
	public void initBox() {
		unionfightbox boxdata = DataCenter.getData(isWin() ? 102 : 101, unionfightbox.class);
		int boxSize = entrySet.size();
		boxSize = boxSize + (6 - boxSize % 3);
		for (int i = 0; i < boxSize; i++) {
			UnionWarBox box = new UnionWarBox();
			box.setReward(Currency.create(CurrencyType.CT_联盟积分, 0, RandomUtility.nextInt(boxdata.getRewardmin(), boxdata.getRewardmax() + 1)));
			getBoxes().add(box);
		}
	}

	public void settle() {
		initBox();
		// 排名奖励
		RankUnionWar rank = new RankUnionWar(getUnionCode());
		ArrayList<RankEntry> top = rankTop(rank);
		rewardRank(top);
	}

	private ArrayList<RankEntry> rankTop(RankUnionWar rank) {
		int min = -1;// 全局最小
		int max = -1;// 全局最大
		Map<String, unionfightrankreward> all = DataCenter.getAllData(unionfightrankreward.class);
		for (unionfightrankreward data : all.values()) {
			if (min < 0 || data.getRankingmin() < min) {
				min = data.getRankingmin();
			}
			if (max < 0 || data.getRankingmax() > max) {
				max = data.getRankingmax();
			}
		}
		return new ArrayList<>(rank.range(min, max));
	}

	private void rewardRank(ArrayList<RankEntry> top) {
		System.err.println("联盟战发排名奖励！！！！" + getUnionCode() + "::" + DateTime.now().toString());
		Map<String, unionfightrankreward> all = DataCenter.getAllData(unionfightrankreward.class);
		for (unionfightrankreward data : all.values()) {
			Collection<Currency> rewards = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());

			for (int i = data.getRankingmin() - 1; i < data.getRankingmax() && i < top.size(); i++) {
				int rank = i + 1;
				RankEntry entry = top.get(i);
				String title = GameString.联盟战排名奖励_title(rank).getText();
				String content = GameString.联盟战排名奖励_msg(rank).getText();
				new MailHandle().sendMail(entry.getKey(), MailTypeEnum.Mail, title, content, CCReason.联盟战, rewards);
			}
		}
		System.err.println("联盟战发排名奖励发完了" + getUnionCode() + "::" + DateTime.now().toString());
	}

	// redis==========================================================================

	static private String key(String unionCode) {
		return String.format("UNION:%s:MODULE:WAR", unionCode);
	}

	public void set() {
		try {
			setv(key(getUnionCode()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	static public UnionWarUnionModule get(String unionCode) {
		try {
			UnionWarUnionModule module = getv(key(unionCode));
			return module;
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static UnionWarUnionModule create(UnionBean unionBean) {
		UnionWarUnionModule module = new UnionWarUnionModule();
		module.setUnionCode(unionBean.getCode());
		module.getEntrySet().addAll(unionBean.members());
		ArrayList<PlayerBean> members = new ArrayList<>();
		for (String playerCode : module.getEntrySet()) {
			PlayerBean playerBean = PlayerBean.get(playerCode);
			if (playerBean == null) {
				continue;
			}
			members.add(playerBean);

			UnionWarPlayerModule unionWarPlayerModule = UnionWarPlayerModule.get(playerCode);
			unionWarPlayerModule.setTimes(0);
			unionWarPlayerModule.setStar(0);
			unionWarPlayerModule.set();
		}
		Collections.sort(members, new Comparator<PlayerBean>() {

			@Override
			public int compare(PlayerBean o1, PlayerBean o2) {
				return o2.getPower() > o1.getPower() ? 1 : -1;
			}
		});

		BattleHandle battleHandle = new BattleHandle();
		int index = 0;
		for (PlayerBean member : members) {
			UnionWarFort fort = new UnionWarFort();
			fort.setIndex(++index);
			fort.setPlayerCode(member.getCode());
			fort.setName(member.getName());
			fort.setLevel(member.getLevel());
			fort.setHead(member.getHead());
			fort.setHeadframe(member.getHeadframe());
			fort.setPower(member.getPower());
			fort.setTeam(battleHandle.teamPlayer(member.getCode(), FormatType.普通));
			module.getForts().add(fort.getPlayerCode());
			UnionWarFort.set(module.getUnionCode(), fort);
			if (index >= 10) {
				break;
			}
		}

		module.setName(unionBean.getName());
		module.setLevel(unionBean.getLevel());
		module.setPower(unionBean.getPower());
		module.set();

		return module;
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:Union:%s", key(getUnionCode()));
	}

}
